package com.vay.de.dang.online.ui.home;

import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;

import com.vay.de.dang.online.VnApp;
import com.vay.de.dang.online.ui.BaseActivity;
import com.vay.de.dang.online.ui.BaseFrag;
import com.vay.de.dang.online.ui.my.HelperCenterActivity;
import com.vay.de.dang.online.util.ResponseHelper;
import com.vay.de.dang.online.util.VnUIManager;
import com.vay.de.dang.online.util.VnUtil;
import com.vay.de.dang.online.view.DialogConfirm;
import com.vay.de.dang.online.view.DialogUpgrade;
import com.vay.de.dang.online.view.DialogWarring;
import com.vay.de.dang.online.web.BaseApi;
import com.vay.de.dang.online.web.LoginApi;
import com.vay.de.dang.online.web.ReqCallback;
import com.vay.de.dang.online.web.ReqResult;
import com.vay.de.dang.online.R;
import com.vay.de.dang.online.entiy.CustomerEntity;
import com.vay.de.dang.online.entiy.AppConfigEntity;
import com.vay.de.dang.online.entiy.CommodityEntity;
import com.vay.de.dang.online.util.VnContext;
import com.vay.de.dang.online.util.CallerUtil;
import com.vay.de.dang.online.databinding.FragmentHomeBinding;
import com.vay.de.dang.online.web.HomeApi;

import java.util.Arrays;
import java.util.List;

public class TabHomeFragment extends BaseFrag {

    private FragmentHomeBinding binding;

    public static TabHomeFragment newInstance() {
        Bundle args = new Bundle();
        TabHomeFragment fragment = new TabHomeFragment();
        fragment.setArguments(args);
        return fragment;
    }

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        binding = FragmentHomeBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

        binding.hrTv.loadTexts(Arrays.asList(""));
        binding.hrTv.startAutoScroll();

        // 下来刷新
        binding.swipeRefresh.setColorSchemeColors(
                ContextCompat.getColor(getContext(), R.color.purple_500)
        );
        binding.swipeRefresh.setOnRefreshListener(() -> {
            queryAppConfig(false);
        });

        binding.scrollView.getViewTreeObserver().addOnScrollChangedListener(() -> {
            binding.swipeRefresh.setEnabled(binding.scrollView.getScrollY() == 0);
        });

        // broadcast
        HomeApi.queryBroadcast(new ReqCallback() {
            @Override
            public void callback(ReqResult value) {
                if (value.isOk()) {
                    List<String> list = (List<String>) value.result;
                    binding.hrTv.loadTexts(list);
                }
            }
        });

        // call service
        binding.homeBntService.setOnClickListener(v -> {
            LoginApi.queryServicePhone(new ReqCallback(getActivity()) {
                @Override
                public void callback(ReqResult value) {
                    if (value.isOk()) {
                        CustomerEntity customer = (CustomerEntity) value.result;
                        new DialogConfirm(getActivity())
                                .setTitleText(R.string.login_service_title)
                                .setHintText(R.string.login_service_hint)
                                .setContentText(customer.getCustomerTelephone() + "\n" + customer.getCustomerEmail())
                                .showConfirm(() -> {
                                    CallerUtil.call(getActivity(), customer.getCustomerTelephone());
                                });
                    }
                }
            }.showDialog(true));
        });

        // 公告
        binding.homeBntBox.setOnClickListener(v -> {
            AppConfigEntity config = VnContext.instance().getAppConfig();
            if (config != null) {
                new DialogWarring(getContext())
                        .setTitleText(R.string.label_notice)
                        .setHintText(config.getAnnouncement())
                        .hideCancel()
                        .showConfirm(() -> {

                        });
            }
        });

        // 帮助中心
        binding.bntHelp.setOnClickListener(v -> {
            VnUIManager.nextActivity(getActivity(), HelperCenterActivity.class);
        });

        // 价值配置
        queryAppConfig(true);

        // 首页曝光
        VnApp.trackEventHomeExposure();

        return root;
    }

    // 单盘
    private void loadSingleView(CommodityEntity entity) {
        binding.topOneLayout.removeAllViews();
        binding.productLayout.removeAllViews();
        binding.moreLayout.setVisibility(View.GONE);
        binding.oneLayout.setVisibility(View.VISIBLE);
        LayoutInflater inflater = getLayoutInflater();

        // 产品
        View iv1 = inflater.inflate(R.layout.item_home_top_product, null);
        TextView pName = iv1.findViewById(R.id.tv_name);
        TextView pMoney = iv1.findViewById(R.id.tv_money);
        pName.setText(entity.getCommodityName());
        pMoney.setText(VnUtil.toMoneyStr2(entity.getMinQuota()) + "-" + VnUtil.toMoneyStr2(entity.getMaxQuota()));
        binding.topOneLayout.addView(iv1);
        // 状态控制
        ResponseHelper.applyButton((BaseActivity) getActivity(),
                entity, iv1.findViewById(R.id.bnt_apply));

        // 帮助
        View iv2 = inflater.inflate(R.layout.item_single_help, null);
        iv2.findViewById(R.id.go_help_layout).setOnClickListener(v -> {
            VnUIManager.nextActivity(getActivity(), HelperCenterActivity.class);
        });
        binding.productLayout.addView(iv2);
    }

    // 贷超
    private void loadMarketView(List<CommodityEntity> list) {
        if (list.isEmpty()) return;

        binding.topOneLayout.removeAllViews();
        binding.productLayout.removeAllViews();
        binding.moreLayout.setVisibility(View.VISIBLE);
        binding.oneLayout.setVisibility(View.GONE);
        LayoutInflater inflater = getLayoutInflater();

        // 第一个产品
        CommodityEntity p1 = list.get(0);
        View iv1 = inflater.inflate(R.layout.item_home_top_product, null);
        TextView pName = iv1.findViewById(R.id.tv_name);
        TextView pMoney = iv1.findViewById(R.id.tv_money);
        pName.setText(p1.getCommodityName());
        pMoney.setText(VnUtil.toMoneyStr2(p1.getMinQuota()) + "-" + VnUtil.toMoneyStr2(p1.getMaxQuota()));
        binding.topOneLayout.addView(iv1);
        // 状态控制
        ResponseHelper.applyButton((BaseActivity) getActivity(), p1, iv1.findViewById(R.id.bnt_apply));

        // 其他商品
        for (int index = 1; index < list.size(); index++) {
            CommodityEntity entity = list.get(index);

            View iv = inflater.inflate(R.layout.item_home_product, null);
            TextView tvName = iv.findViewById(R.id.tv_name);
            TextView tvMoney = iv.findViewById(R.id.tv_money);
            TextView periods = iv.findViewById(R.id.tv_periods);

            tvName.setText(entity.getCommodityName());
            tvMoney.setText(VnUtil.toMoneyStr2(entity.getMinQuota()) + "-" + VnUtil.toMoneyStr2(entity.getMaxQuota()));
            periods.setText(entity.getMinLoanTerm() + "-" + entity.getMaxLoanTerm() + "Days");

            // 状态控制
            ResponseHelper.applyButton((BaseActivity) getActivity(), entity, iv.findViewById(R.id.bnt_apply));
            binding.productLayout.addView(iv);
        }
    }

    // 重新价值数据
    public void queryAppConfig(boolean showDialog) {

        // home config
        HomeApi.queryAppConfig(new ReqCallback() {
            @Override
            public void callback(ReqResult value) {
                if (value.isOk()) {
                    AppConfigEntity entity = (AppConfigEntity) value.result;
                    int versionUpdate = entity.getVersionUpdate();
                    String remoteVersion = entity.getVersion();
                    String url = entity.getAppUrl();
                    String content = entity.getVersionInfo();
                    int isGoogleUpdate = entity.getIsGoogleUpdate();

                    String versionName = "0.0.1";
                    try {
                        PackageManager packageManager = getActivity().getPackageManager();
                        PackageInfo packInfo = packageManager.getPackageInfo(getActivity().getPackageName(), 0);
                        versionName = packInfo.versionName;
                    } catch (Exception var2) {
                    }

                    if (!VnUtil.isEmpty(versionName)) {
                        BaseApi.log("LocalVersion: " + versionName + "; RemoteVersion: " + remoteVersion);

                        // 本地版本
                        int serverVersion = VnUtil.toVersionName(remoteVersion);
                        int localVersion = VnUtil.toVersionName(versionName);

                        if (serverVersion > localVersion
                                && (versionUpdate == 1 || isGoogleUpdate == 1)) {
                            new DialogUpgrade(getActivity())
                                    .showUpgrade(versionUpdate, isGoogleUpdate, remoteVersion, content, url);
                        }
                    }

                    /*if (!VnUtil.isEmpty(entity.getSceNo())) {
                        binding.sceNo.setVisibility(View.VISIBLE);
                        binding.sceNo.setText(entity.getSceNo());
                    }*/
                }
            }
        });

        // 首页商品
        HomeApi.queryHomeCommodity(new ReqCallback(getActivity()) {

            @Override
            public void callback(ReqResult value) {
                if (value.isOk()) {
                    List<CommodityEntity> list = (List<CommodityEntity>) value.result;
                    // 单盘
                    if (list.size() == 1) {
                        loadSingleView(list.get(0));
                    } else {
                        loadMarketView(list);
                    }
                }
            }

            @Override
            public void end() {
                super.end();
                binding.swipeRefresh.setRefreshing(false);
            }

        }.showDialog(showDialog));
    }

    public void reload() {
        binding.swipeRefresh.setRefreshing(true);
        queryAppConfig(false);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
}